#!/usr/bin/env python

'''
program that will compare Rajiv's data with my simulations
'''

import os
import sys
import matplotlib.pyplot

sys.path += ['..']

import common
import re
import math
import scipy

Rajiv_folder = os.path.join('..', '..', 'Entropy_Analysis_made_by_Rajiv', 'two_d_triang')

case = common.choice(Rajiv_folder)

beta = []
S = []

p = re.compile(r'[\w-]+h(\d+)[\w-]+')

B = float(p.search( case).group(1))
print B

for line in open(os.path.join(Rajiv_folder, case)):
    temp = line.strip().split()
    beta += [ eval(temp[0]) ]
    S += [ eval(temp[1]) ]
    
    
T = [1 / tx for tx in beta]

T.reverse()
S.reverse()

#I'll imit my graph to T = 10

for t, Value in enumerate(T):
    if Value > 10:        
        Tindex = t
        break  

matplotlib.pyplot.plot(T[ :Tindex], S[:Tindex], label = 'from series expansion')
matplotlib.pyplot.xlabel("$T$")
matplotlib.pyplot.ylabel('$S$')

#Now we should get data from simulations

path = os.path.join('..', '..', 'results', 'two_d_triang', 'J_1.0', 'B_{}'.format(B), 'N16', 'dT0.05')

def Entropy(T, E):
    '''
    returns entropy
    '''
    beta = [1 / tt for tt in T]
    S = []
    for i in xrange(len(E)):
        S += [ math.log(2) + E[i] / T[i] + scipy.trapz(E[i:], beta[i:]) ]
        
    minS = S[0]
    return [ts - minS for ts in S]    

ttList = os.listdir( os.path.join(path, 'Energy_J') )

tList = []
Energy = []
result = []

for T in os.listdir( os.path.join(path, 'Energy_J') ):
    E_J = eval(open(os.path.join(path, 'Energy_J', T)).read())
    E_B = eval(open(os.path.join(path, 'Energy_B', T)).read())
    
    result += [ (eval(T.replace('T', '')), E_J + E_B) ]
    #Energy += [ E_J + E_B ]
    #tList += [ eval(T.replace('T', '')) ]

result.sort()

tList = [tx[0] for tx in result]
Energy = [tx[1] for tx in result]

S = Entropy( tList, Energy )

matplotlib.pyplot.plot(tList, S, '*', label = 'from simulation')

matplotlib.pyplot.legend(loc = 'upper left')


matplotlib.pyplot.show()
